package com.xius.service;

import cn.hutool.core.convert.Convert;
import com.xius.dao.SecPermissionDao;
import com.xius.dao.SecRoleDao;
import com.xius.dao.SecUserDao;
import com.xius.entity.field.SecRoleField;
import com.xius.entity.field.SecUserField;
import com.xius.entity.model.Permission;
import com.xius.entity.model.User;
import com.xius.vo.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 自定义UserDetails查询
 * </p>
 *
 * @author yangkai.shen
 * @date Created in 2018-12-10 10:29
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private SecUserDao secUserDao;

    @Autowired
    private SecRoleDao secRoleDao;

    @Autowired
    private SecPermissionDao secPermissionDao;

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmailOrPhone) throws UsernameNotFoundException {
        // TODO 有问题
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.clear();
        userMap.put(SecUserField.SEC_USER_USERNAME,usernameOrEmailOrPhone);
        userMap.put(SecUserField.SEC_USER_EMAIL,usernameOrEmailOrPhone);
        userMap.put(SecUserField.SEC_USER_PHONE,usernameOrEmailOrPhone);
        Map<String,Object> user = secUserDao.queryByUsernameOrEmailOrPhone(userMap);
        Optional.ofNullable(user).orElseThrow(() -> new UsernameNotFoundException("未找到用户信息 : " + usernameOrEmailOrPhone));

        Long userId = (Long) user.get(SecUserField.SEC_USER_ID);
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        List<Map<String, Object>> roles = secRoleDao.selectByUserId(userId);
        List<Long> roleIds = roles.stream()
                .map(map1->Convert.toLong(map1.get(SecRoleField.SEC_ROLE_ID)))
                .collect(Collectors.toList());
        List<Map<String,Object>> permissions = secPermissionDao.selectByRoleIdList(roleIds);
        //

        return UserPrincipal.create(user, roles, permissions);
    }
}
